/*
 * Copyright 2018 peipeihh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * limitations under the License.
 */
package com.pphh.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by huangyinhuang on 3/19/2018.
 */
@SpringBootApplication
@RestController
public class UserApp {

    public static void main(String[] args) {
        SpringApplication.run(UserApp.class, args);
    }

    @PostMapping(value = "/api/login")
    public String login(@RequestBody UserInfo userInfo,
                        HttpServletRequest request,
                        HttpServletResponse response) {

        CookieUtils.printCookies(request);

        CookieUtils.setCookie(response, DemoProperties.cookieUserName, userInfo.getUserName(), DemoProperties.cookieDomain,
                DemoProperties.cookiePath, DemoProperties.cookieSecure, DemoProperties.cookieExpiry);
        CookieUtils.setCookie(response, DemoProperties.cookieUserRole, userInfo.getUserRole(), DemoProperties.cookieDomain,
                DemoProperties.cookiePath, DemoProperties.cookieSecure, DemoProperties.cookieExpiry);

        return "succeeded to login. please view login user info in browser cookies.";
    }

    @PostMapping(value = "/api/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {

        // remove the cookie by setting the expiry as 0
        CookieUtils.setCookie(response, DemoProperties.cookieUserName, "", DemoProperties.cookieDomain,
                DemoProperties.cookiePath, DemoProperties.cookieSecure, 0);

        CookieUtils.setCookie(response, DemoProperties.cookieUserRole, "", DemoProperties.cookieDomain,
                DemoProperties.cookiePath, DemoProperties.cookieSecure, 0);

        return "succeeded to logout. please view login user info in browser cookies.";
    }

}
